const chunk = require('lodash.chunk');
const Record = require('../Model/RecordSchema');

//获取当前月的day of the week  [Sunday - Saturday : 0 - 6]
const getFirstDayOfWeek = (year, month) => {
  const date = new Date(year, month, 0);
  date.setDate(1);
  return date.getDay();
}

// 获取某个月的总天数
const getDaysOfMonth = (year, month) => {
  const date = new Date(year, month, 0);
  const days = date.getDate();
  return days;
}

//获取当前月份的总天数
const getDays = () => {
  const date = new Date();
  //将当前月份加1，下移到下一个月
  date.setMonth(date.getMonth() + 1);
  //将当前的日期置为0，
  date.setDate(0);
  const days = date.getDate();
  return days;
}

const generateRawMonthCalendar = (year = new Date().getFullYear(), month = new Date().getMonth() + 1) => {
  const rawArr = new Array(getDaysOfMonth(year, month))
    .fill(0)
    .map((item, index) => index + 1);
  const firstDayofWeek = getFirstDayOfWeek(year, month);
 
  rawArr.unshift(...new Array(firstDayofWeek).fill(0));
  return rawArr;
}

const generateMonthCalendar = (record, year, month) => {
  const rawArr = generateRawMonthCalendar(year,month);
  let idx = 0, start=0;
  const resCalendar = rawArr.map((item)=>{
    return [item,0]
  });
  if(record){
    while(idx<record.length) {
      if(rawArr[start] === record[idx]) {
        ++idx;
        resCalendar[start][1]=1;
      }
      ++start;
    }
  }
  return chunk(resCalendar,7);
}

module.exports = {
  generateMonthCalendar
}



